package com.example.homelicaisystem.control;

import com.example.homelicaisystem.entity.*;
import com.example.homelicaisystem.entity.DTO.FamilyDTO;
import com.example.homelicaisystem.entity.DTO.IncomeDetailDTO;
import com.example.homelicaisystem.entity.DTO.UserDTO;
import com.example.homelicaisystem.services.FamilyService;
import com.example.homelicaisystem.services.IncomeDetailService;
import com.example.homelicaisystem.services.UserService;
import com.example.homelicaisystem.utils.HandleMoney;
import com.example.homelicaisystem.utils.Result;
import com.example.homelicaisystem.utils.UserUtil;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/family")
@RestController
@Slf4j
public class FamilyControl {
    private final FamilyService familyService;
    private final UserService userService;
    private final IncomeDetailService incomeDetailService;

    public FamilyControl(FamilyService familyService, UserService userService, IncomeDetailService incomeDetailService) {
        this.familyService = familyService;
        this.userService = userService;
        this.incomeDetailService = incomeDetailService;
    }

    @GetMapping("/listMember")
    public Result<List<User>> getListMember() {
        log.debug("收到listMember请求。");
        User user = userService.getUserById(UserUtil.getUserId());
        return Result.ok(familyService.getList(user.getFamilyId()));
    }

    @PostMapping("/add")
    public Result<?> addFamilyMember(@RequestBody User data) {
        log.debug("收到create请求");
        //获取当前用户的家庭id
        User user = userService.getUserById(UserUtil.getUserId());
        data.setFamilyId(user.getFamilyId());
        //创建家庭成员，并包含当前家庭id
        data.setPassword("123456");
        userService.create(data);
        //获取创建的家庭成员
        User createUser = userService.getUserByPhone(data.getPhone());
        //初始化创建用户的权限
        userService.initializeFamilyMemberPower(createUser);
        return Result.ok(null);
    }

    @PostMapping("/listIncome")
    public Result<List<IncomeDetail>> getListIncomeMonth(@RequestBody FamilyDTO data) {
        log.debug("收到listIncome请求。");
        //根据收入方式mode获取月份的收入

        List<IncomeDetail> list = incomeDetailService.censusByMode(data);
        //处理显示的金钱数据
        list.forEach(incomeDetail -> {
            incomeDetail.setMoney(HandleMoney.showMoney(incomeDetail.getMoney()));
        });
        return Result.ok(list);

    }

    @PostMapping("/listExpend")
    public Result<List<ExpendDetail>> getListExpendMonth(@RequestBody FamilyDTO data){

        return Result.ok(null);
    }
}
